package org.ghost.springboot.demo.common.component;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Locale;

@Component
public class RequestContext implements IRequestContext {
    private static final Logger logger = LoggerFactory.getLogger(RequestContext.class);

    private static final ThreadLocal<RequestContext> CONTEXT = new ThreadLocal<>();

    private String id;

    private Locale locale = Locale.SIMPLIFIED_CHINESE;

    private String clientIp;

    private long beginTime;

    private static InetAddress inetAddress = null;

    public static RequestContext getContext() {
        RequestContext result = CONTEXT.get();

        if (result == null) {
            result = new RequestContext();
            CONTEXT.set(result);
        }

        return result;
    }


    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public static void remove() {
        CONTEXT.remove();
    }


    public Locale getLocale() {
        return locale;
    }

    public void setLocale(Locale locale) {
        this.locale = locale;
    }

    public String getClientIp() {
        return clientIp;
    }

    public void setClientIp(String clientIp) {
        this.clientIp = clientIp;
    }

    public long getBeginTime() {
        return beginTime;
    }

    public void setBeginTime(long beginTime) {
        this.beginTime = beginTime;
    }

    public static String getHostAddress() {
        if (inetAddress == null) {
            synchronized (logger) {
                if (inetAddress == null) {
                    try {
                        inetAddress = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        logger.error("*****RequestContext.getHostAddress报错:" + e.getMessage(), e);
                    }
                }
            }
        }

        if (inetAddress != null) {
            return inetAddress.getHostAddress();
        }

        return null;
    }
}
